﻿using System;
using System.Collections.Generic;
#if DEBUG
using System.Diagnostics;
#endif // #if DEBUG
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using FRL.DebtChased.Repository;
using FRL.DebtChased.Repository.ViewModels;
using FRL.DebtChased.Website;

namespace WebApplication.Finance
{

	/// <summary>
	/// Declaration of AccountTradingStyleList
	/// </summary>
	public partial class AccountTradingStyleList : System.Web.UI.Page
	{

		/////////////////////////////////////////////////////////////
		// Constants

		private const string ContextModeltag = "ContextModel";

		/////////////////////////////////////////////////////////////
		// Attributes

		private AccountTradingStyleModel m_contextModel;
		private AccountTradingStyleModel ContextModel
		{
			get
			{
				if (m_contextModel == null)
					m_contextModel = ViewState[ContextModeltag] as AccountTradingStyleModel;
				return m_contextModel;
			}
			set
			{
				ViewState[ContextModeltag] = value;
			}
		}

		/////////////////////////////////////////////////////////////
		// Event handlers

		protected void Page_Load(object sender, EventArgs e)
		{

			// If this is a postback...
			if (this.IsPostBack)
			{

				// Get the model
				AccountTradingStyleModel model = ContextModel;
#if DEBUG
				Debug.Assert(model != null);
#endif // #if DEBUG

				// Update model from grid				
#if DEBUG
				Debug.Assert(gridTradingStyle.Rows.Count == model.Elements.Count);
#endif // #if DEBUG
				for (int iRowIndex = 0; iRowIndex < gridTradingStyle.Rows.Count; iRowIndex++)
				{

					// Get the id and text
					int id = int.Parse(gridTradingStyle.DataKeys[iRowIndex].Value.ToString());
					TextBox txtName = gridTradingStyle.Rows[iRowIndex].FindControl("txtName") as TextBox;

					// Update model from grid controls
					model.SetName(id,txtName.Text);

				}

			}
			else
			{
#if DEBUG
				Debug.Assert(ContextModel == null);
#endif // #if DEBUG

				// Declare an entities object
				using (DebtChasedEntities ent = new DebtChasedEntities())
				{

					// Load the workflow list model
					ContextModel = new AccountTradingStyleModel(ent);

				}

			}

			// Bind the grid to the data
			gridTradingStyle.DataSource = ContextModel.Elements;
			gridTradingStyle.DataBind();

		}

		protected void gridTradingStyle_RowDataBound(object sender, GridViewRowEventArgs e)
		{

			// If this is a data-row...
			if (e.Row.RowType == DataControlRowType.DataRow)
			{

				// Get the model element
				AccountTradingStyleModel.Element el = e.Row.DataItem as AccountTradingStyleModel.Element;

				// Load the workflow drop-down
				TextBox txtName = e.Row.FindControl("txtName") as TextBox;
				txtName.Text = el.Name;

				// Get the delete button
				if (el.InUse)
				{
					DataControlFieldCell cell = e.Row.Cells[3] as DataControlFieldCell;
					cell.Enabled = false;
				}

			}

		}

		protected void gridTradingStyle_RowCommand(object sender, GridViewCommandEventArgs e)
		{

			// Check the grid view object
			GridView gridView = sender as GridView;
#if DEBUG
			System.Diagnostics.Trace.Assert(gridView == gridTradingStyle);
#endif // #if DEBUG

			// Get row index
			int iRow = int.Parse(e.CommandArgument.ToString());

			// Convert argument to id
			int iAccountInvoiceStatusId = int.Parse(gridTradingStyle.DataKeys[iRow].Value.ToString());

			// Compare commands
			if (e.CommandName == "DeleteStyle")
			{

				// Delete the row from the model and re-bind
				AccountTradingStyleModel model = ContextModel;
				model.Elements.RemoveAt(iRow);
				gridTradingStyle.DataSource = ContextModel.Elements;
				gridTradingStyle.DataBind();

			}

		}

		protected void butRevert_Click(object sender, EventArgs e)
		{

			// Return to the workflows page
			this.Reload();

		}

		protected void butOK_Click(object sender, EventArgs e)
		{

			// Get the user id
			int iUserId = MySession.BindMySession().UserID;
#if DEBUG
			if(iUserId==0)
				iUserId = 1;
#endif // #if DEBUG

			// Get the context model
			AccountTradingStyleModel model = ContextModel;

			// Declare an entities object
			using (DebtChasedEntities ent = new DebtChasedEntities())
			{

				// Save the content
				string strError = model.Set(ent, iUserId);
				if (strError == null)
					this.Reload();
				else
					(Page.Master as FinanceMaster).ErrorMessage = strError;

			}

		}

		protected void butAddNew_Click(object sender, EventArgs e)
		{

			// Track errors
			string strError = null;

			// Get the context model
			AccountTradingStyleModel model = ContextModel;

			// Add a new status to the list
			string strName = txtNewName.Text.Trim();

			// If the name is NOT valid...
			if (strName.Length < 3)
				strError = "The style name must be 3 characters or more.";

			// If that worked...
			if(strError==null)
			{

				// Find if this name is already in use
				bool bFound = false;
				foreach (AccountTradingStyleModel.Element el in model.Elements)
				{
					if (string.Compare(el.Name, strName, true) == 0)
					{
						bFound = true;
						break;
					}
				}

				// If name found...
				if(bFound)
					strError = string.Format("The trading style name \"{0}\" is already in use.", strName);

			}

			// If that worked...
			if (strError == null)
			{

				// Pick a new id to identify element
				int iNewId = 0;
				foreach (AccountTradingStyleModel.Element el in model.Elements)
					iNewId = Math.Min(iNewId, el.AccountTradingStyleId);
				iNewId--;

				// Add to the context model
				model.Elements.Add(new AccountTradingStyleModel.Element(iNewId, strName));

				// Bind the grid to the data
				gridTradingStyle.DataSource = ContextModel.Elements;
				gridTradingStyle.DataBind();

			}

			// Set error
			if(strError!=null)
				(Page.Master as FinanceMaster).ErrorMessage = strError;

		}

	}

}
